package www.ld.com.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import javax.annotation.Resource;

@Configuration
@RefreshScope
@EnableConfigurationProperties(JWTProperties.class)
public class TokenStoreConfig {
    private final JWTProperties properties;
    @Resource
    private CustomerAccessTokenConverter customerAccessTokenConverter;

    TokenStoreConfig(JWTProperties properties) {
        this.properties = properties;
    }

    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        final ClassPathResource resource = new ClassPathResource(properties.getResourceName());
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(resource, properties.getPassword().toCharArray());
        converter.setKeyPair(factory.getKeyPair(properties.getAlias()));
        converter.setAccessTokenConverter(customerAccessTokenConverter);
        return converter;
    }
}
